package com.huewu.pla.pinterest;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import opens.components.http.HttpObjectRequest;
import opens.components.http.core.HttpRequest;
import opens.components.http.core.RequestQueue;

import org.apache.http.HttpResponse;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.flurry.android.FlurryAgent;
import com.huewu.pla.lib.MultiColumnListView;
import com.huewu.pla.lib.internal.PLA_AdapterView;
import com.huewu.pla.lib.internal.PLA_AdapterView.OnItemClickListener;
import com.huewu.pla.lib.internal.PLA_AdapterView.OnItemLongClickListener;
import com.huewu.pla.pinterest.internal.ImageWrapper;
import com.huewu.pla.pinterest.internal.SimpleViewBuilder;
import com.idreems.model.JionServerData;
import com.idreems.model.ServerDataDecoder;
import com.idreems.zakerlike.MyApplication;
import com.idreems.zakerlike.R;
import com.idreems.zakerlike.util.Util;
import com.lurencun.android.adapter.AbstractAdapter;
import com.lurencun.android.adapter.CommonAdapter;

public class PinterestActivity extends Activity {
    private static final String TAG = "PinterestActivity";
    protected AbstractAdapter<ImageWrapper> mAdapter = null;
    public static final int PULL_TO_REFRESH_ID = 1008611;
    protected MultiColumnListView mWaterfallView = null;

    private JionServerData mJsonKeyGroup;
    private ProgressBar mBar;
    private int mPage = 1;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    private int getWaterfallViewColumnCount()
    {
    	return 1;
//        final int kSingleColumnWidth = 240;
//        DisplayMetrics dm=new DisplayMetrics(); 
//        getWindowManager().getDefaultDisplay().getMetrics(dm); 
//        return (dm.widthPixels-dm.widthPixels%kSingleColumnWidth)/kSingleColumnWidth;
    }
    protected void init() {
        setContentView(R.layout.pinterest);
        mWaterfallView = (MultiColumnListView) findViewById(R.id.list);
        mWaterfallView.setColumnCount(getWaterfallViewColumnCount());
        Intent intent = getIntent();
        if (null != intent) {
            Serializable obj = intent.getSerializableExtra(ServerDataDecoder.kJsonkeyWrapper);
            if (obj instanceof JionServerData) {
                mJsonKeyGroup = (JionServerData) obj;
            }
        }
        if (null == mJsonKeyGroup) {
            mJsonKeyGroup = new JionServerData();
        }
        mBar = (ProgressBar) findViewById(R.id.progessbar);
        mBar.setIndeterminate(true);
        reload(mPage);

        mWaterfallView.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(PLA_AdapterView<?> parent, View view, int position, long id) {
                final ImageWrapper wrapper = (ImageWrapper) parent.getItemAtPosition(position);
                Log.d(TAG, "position :" + position + " " + wrapper.description);
                FlurryAgent.logEvent(Util.kFlurryEventOnItemShare);
                new AlertDialog.Builder(PinterestActivity.this)
                        .setTitle(R.string.share_title)
                        .setItems(getResources().getStringArray(R.array.share2friend), new OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Util.share(wrapper, PinterestActivity.this);
                            }
                        }).show();
                return false;
            }
        });

        mWaterfallView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(PLA_AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getApplicationContext(), PhotoViewActivity.class);
                ImageWrapper wrapper = (ImageWrapper) parent.getItemAtPosition(position);

                if (null != wrapper && !TextUtils.isEmpty(wrapper.largeUrl)) {
                    intent.putExtra(PhotoViewActivity.kURL, wrapper.largeUrl);

                    if (view instanceof ViewGroup) {
                        ViewGroup viewGroup = (ViewGroup) view;
                        // find imageview
                        for (int i = 0; i < viewGroup.getChildCount(); i++) {
                            View v = viewGroup.getChildAt(i);
                            if (v instanceof ImageView) {
                                ImageView imageView = ((ImageView) v);
                                BitmapDrawable bitmapDrawable = ((BitmapDrawable) imageView.getDrawable());
                                if (null != bitmapDrawable) {
                                    intent.putExtra(PhotoViewActivity.kPlaceholderImage, bitmapDrawable.getBitmap());
                                    break;
                                }
                            }
                        }

                    }
                    startActivity(intent);
                }
            }
        });

        // ///////////////////////////////////////////////////////////////////////
        // 初始化第三个广告条[右下角]
        Util.loadBannerAds(this, R.id.adLayout, false);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(Menu.NONE, PULL_TO_REFRESH_ID, 0, getString(R.string.refresh_load_more));
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == PULL_TO_REFRESH_ID) {
            // Intent intent = new Intent(this, PullToRefreshPinterestActivity.class);
            // startActivity(intent);
            reload(++mPage);
        }
        return true;
    }

    protected void reload(int page) {
        final int kInitPage = 1;
        TimelineRequest request = new TimelineRequest();
        request.get(mJsonKeyGroup.url(page));
        request.setCache(MyApplication.getCache());
        if (page != kInitPage) {
            request.setCachePolicy(HttpRequest.DoNotReadFromCacheCachePolicy|HttpRequest.FallbackToCacheIfLoadFailsCachePolicy);
        }
        request.onSuccess(this, "onTimelineRequestSuccess");
        request.onError(this, "onTimelineRequestError");
        RequestQueue.instance().push(request);
        mBar.setVisibility(View.VISIBLE);
    }

    public class TimelineRequest extends HttpObjectRequest<List<ImageWrapper>> {

        @Override
        protected void onHttpResponseReceived(HttpResponse response) throws Exception {
            List<ImageWrapper> timeline = mJsonKeyGroup.decode(getString(response));
            setResponseObject(timeline);
        }
    }

    @SuppressWarnings("unused")
    private void onTimelineRequestError(TimelineRequest request) {
        mBar.setVisibility(View.GONE);
        Toast.makeText(getApplicationContext(), getString(R.string.network_unavailable), Toast.LENGTH_SHORT).show();
    }

    @SuppressWarnings("unused")
    private void onTimelineRequestSuccess(TimelineRequest request) {
        List<ImageWrapper> timeline = request.getResponseObject();
        if (null == mAdapter) {
            mAdapter = new CommonAdapter<ImageWrapper>(getLayoutInflater(), new SimpleViewBuilder());
            mAdapter.add(timeline);
            mWaterfallView.setAdapter(mAdapter);
            // add items
            for (ImageWrapper imageWrapper : timeline) {
                mImageUrlSet.add(TextUtils.isEmpty(imageWrapper.url) ? imageWrapper.description : imageWrapper.url);
            }
        } else {
            List<ImageWrapper> uniqueItems = new ArrayList<ImageWrapper>();
            for (ImageWrapper imageWrapper : timeline) {
                if (mImageUrlSet.contains(TextUtils.isEmpty(imageWrapper.url) ? imageWrapper.description : imageWrapper.url)) {
                    continue;
                }
                mImageUrlSet.add(TextUtils.isEmpty(imageWrapper.url) ? imageWrapper.description : imageWrapper.url);
                uniqueItems.add(imageWrapper);
            }
            mAdapter.add(uniqueItems);
        }

        mBar.setVisibility(View.GONE);
    }

    private Set<String> mImageUrlSet = new HashSet<String>();// prevent duplicate image in ui
}// end of class
